package com.epam.cdp.selenium2.core.configuration;

import java.util.ArrayList;

import com.epam.cdp.selenium2.core.exception.ItemNotFoundException;

/**
 * Configuration of SeleniumRC parameters.
 * 
 * @author yyudzitski
 */
public class SeleniumConfiguration
{
  private SeleniumInstanceConfiguration defaultConfiguration;

  private SeleniumInstanceConfiguration currentConfiguration;

  private ArrayList<SeleniumInstanceConfiguration> additionalConfigurations;

  public SeleniumConfiguration()
  {
    defaultConfiguration = new SeleniumInstanceConfiguration();
    currentConfiguration = new SeleniumInstanceConfiguration();
    additionalConfigurations = new ArrayList<SeleniumInstanceConfiguration>();
  }

  /**
   * Set current configuration to default.
   */
  public void resetConfiguration()
  {
    currentConfiguration = defaultConfiguration;
  }

  public SeleniumInstanceConfiguration getDefaultConfiguration()
  {
    return defaultConfiguration;
  }

  public SeleniumInstanceConfiguration getCurrentConfiguration()
  {
    /** Check is current configuration initialized */
    if( currentConfiguration.getConfigName() == null )
    {
      currentConfiguration = defaultConfiguration;
    }
    return currentConfiguration;
  }

  /**
   * Set list of additional configuration if it not set. You can't set new list if there are not empty list of
   * additional configuration.
   * 
   * @param additionalConfigurations
   */
  public void setAdditionalConfigurations( ArrayList<SeleniumInstanceConfiguration> additionalConfigurations )
  {
    if( this.additionalConfigurations.isEmpty() )
    {
      this.additionalConfigurations = additionalConfigurations;
    }
  }

  /**
   * Find SeleniumRC configuration in additional configuration by it name
   * 
   * @param configName
   * @throws ItemNotFoundException
   * @return
   */
  public SeleniumInstanceConfiguration findConfiguration( String configName )
  {
    for( SeleniumInstanceConfiguration config : additionalConfigurations )
    {
      if( config.getConfigName().equals( configName ) )
      {
        return config;
      }
    }
    throw new ItemNotFoundException( "Config not found: " + configName );
  }

  /**
   * Set one of additional SeleniumRC configuration as current.
   * 
   * @param configName
   */
  public void setAdditionalConfigToCurrent( String configName )
  {
    SeleniumInstanceConfiguration newConfig = findConfiguration( configName );
    if( !newConfig.getConfigName().equals( currentConfiguration.getConfigName() ) )
    {
      currentConfiguration = newConfig;
    }
  }
}